﻿using Manon.Core.Commons;
using Manon.Core.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Manon.Core.Filters
{
    public class ApiResultAsyncFilter : IAsyncResultFilter
    {


        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result == null)
            {
                await next();
                return;
            }

            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                var errMsg = modelState.Values.SelectMany(x => x.Errors?.Select(y => y.ErrorMessage) ?? new List<string>());

                context.Result = new JsonResult(new ApiResult()
                {
                    Success = false,
                    StatusCode = StateCode.Error.GetHashCode(),
                    Message = String.Join(";", errMsg)
                });
                // 如果模型验证的时候直接返回
                return;
            }

            if (context.Result is ObjectResult objectResult)
            {
                context.Result = new JsonResult(ApiResult.SuccessResult(context, objectResult.Value));
            }
            else if (context.Result is JsonResult jsonResult)
            {
                context.Result = new JsonResult(ApiResult.SuccessResult(context, jsonResult.Value));
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new JsonResult(new ApiResult()
                {
                    Success = false,
                    StatusCode = StateCode.NotFound.GetHashCode(),
                    Message = "未找到资源"
                });
            }

            await next();

        }
    }
}
